package com.uikoo9.manage.y.util;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Locale;

/**
 * Created with IntelliJ IDEA.
 * User: shoko (fbjia.com)
 * Date: 13-11-14
 * Time: 上午10:01
 * To change this template use File | Settings | File Templates.
 */


/**
 * 映射数据库，自动生成Entity
 * @author WWF
 */
public class CreateJfinalEntityUtil {

    private static Connection conn = null;
    private static final String URL;
    private static final String JDBC_DRIVER;
    private static final String USER_NAME;
    private static final String PASSWORD;
    private static final String DATABASENAME;
    private static final String PACKAGENAME;
    private static final String PROJECT = "/JFdemo";
    static {
        DATABASENAME = "yready";
        URL = "jdbc:mysql:///"+DATABASENAME;
        JDBC_DRIVER = "com.mysql.jdbc.Driver";
        USER_NAME = "root";
        PASSWORD = "";
        PACKAGENAME = "com.yready.entity";
    }

    /**
     * 获得连接
     * @return
     */
    public static Connection getConnection() {
        try {
            Class.forName(JDBC_DRIVER);
            conn = java.sql.DriverManager.getConnection(URL, USER_NAME, PASSWORD);
        } catch (java.lang.ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 关闭数据库
     */
    public static void closeConnection(){
        try {
            if (conn != null && !conn.isClosed()) {
                conn.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成字段静态声明
     * @param tableName
     * @return
     */
    private static String CreateEntityString(String tableName){
        String result  = "package "+PACKAGENAME+";\n\n";
        result += "import com.jfinal.plugin.activerecord.Model; \n\n";
        result += "public class "+StringUtil.toLowerCaseTheFristChar(tableName)+" extends Model<"+StringUtil.toLowerCaseTheFristChar(tableName)+">{\n\n";
        result += "    private static final long serialVersionUID = 1L;\n";
        result += "    public static final "+StringUtil.toLowerCaseTheFristChar(tableName)+" dao = new "+StringUtil.toLowerCaseTheFristChar(tableName)+"();\n\n";
        result += "    /**表名**/ \n" ;
        result += "    public static String TABLE = \""+tableName+"\";" ;
        String sql = "select column_name from information_schema.columns where TABLE_SCHEMA = '"+DATABASENAME+"' and table_name = '"+tableName+"';";
        try {
            java.sql.Statement statement = conn.createStatement();
            java.sql.ResultSet resultSet =  statement.executeQuery(sql);
            while (resultSet.next()) {
                if (resultSet.getString(1)!=null&&!resultSet.getString(1).isEmpty()) {
                    String string = resultSet.getString(1);
                    String row = "    public static final String "+ string.toUpperCase(Locale.CHINA) +" = \""+string+"\";";
                    String note = "    /****/";
                    result += "\n"+note + "\n" +row;
                }
            }
            resultSet.close();
            statement.close();
            result+="\n }";
            return result;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获得数据库的所有表名
     * @return
     */
    public static java.util.List<String> getAllTables(){//todo 这里需要改进 支持mysql
        String sql = "select relname as TABLE_NAME from pg_class c " +
                "where  relkind = 'r' and relname not like 'pg_%' and relname not like 'sql_%' order by relname";
        if(JDBC_DRIVER.equals("com.mysql.jdbc.Driver")){
            sql = "show tables";
        }
        try {
            java.util.List<String> result = new java.util.ArrayList<String>();
            java.sql.Statement statement = conn.createStatement();
            java.sql.ResultSet resultSet =  statement.executeQuery(sql);
            while (resultSet.next()) {
                if (resultSet.getString(1)!=null&&!resultSet.getString(1).isEmpty()){
                    result.add(resultSet.getString(1));
                }
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }



    /**
     * 生成Entity
     */
    public static void CreateEntity(){
        try {
            getConnection();
            java.util.List<String> tables = getAllTables();
            for (int i = 0; i < tables.size(); i++) {
                java.io.File createFolder = new java.io.File(java.lang.System.getProperty("user.dir")+PROJECT+"/src/"+PACKAGENAME.replace(".", "/"));
                //路径不存在，生成文件夹
                if (!createFolder.exists()) {
                    createFolder.mkdirs();
                }
                String entityString = CreateEntityString(tables.get(i).trim());
                java.io.File entity = new java.io.File(createFolder.getAbsolutePath()+"/"+StringUtil.toLowerCaseTheFristChar(tables.get(i))+".java");
                if (!entity.exists())
                {
                    //写入文件
                    java.io.BufferedWriter out = new java.io.BufferedWriter(new java.io.FileWriter(entity, true));
                    out.write(entityString);
                    out.close();
                    out = null;
                    entity = null;
                }
            }
            closeConnection();
            java.lang.System.out.println("生成成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    public static void main(String[] args) {
        CreateEntity();
    }



}
